﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace Campaign_Manager
{
    class Databases
    {
        SQLiteConnection dataCampaign;
        SQLiteConnection dataGameData;

        public Databases()
        {
            dataCampaign = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/data/campaign.db;");
            dataGameData = new SQLiteConnection("Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "/data/gamedata.db;");
            dataGameData.Open();
        }

        public bool WriteCampaign(string Name, string Creator, bool Locked, string Password)
        {
            try
            {
                dataCampaign.Open();
                SQLiteCommand command = dataCampaign.CreateCommand();
                if (Locked)
                    command.CommandText = "INSERT INTO campaigns (name, creator, created, locked, password) VALUES ('" + Name + "', '" + Creator + "', " + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Year.ToString() + ", 1, '" + Password + "');";
                else
                    command.CommandText = "INSERT INTO campaigns (name, creator, created, locked) VALUES ('" + Name + "', '" + Creator + "', " + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Year.ToString() + ", 0);";
                command.ExecuteNonQuery();
            }
            catch (SQLiteException)
            {
                dataCampaign.Close();
                return false;
            }
            finally
            {
                dataCampaign.Close();
            }
            return true;
        }

        public object[] Monsters(string CR)
        {
            List<object> items = new List<object>();
            SQLiteCommand command = dataGameData.CreateCommand();
            command.CommandText = "SELECT Name FROM bestiary WHERE CR = '" + CR + "';";
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                items.Add((string)reader["Name"]);
            }
            return items.ToArray();
        }

        public string MonsterInfo(string Name)
        {
            SQLiteCommand command = dataGameData.CreateCommand();
            command.CommandText = "SELECT FullText FROM bestiary WHERE Name = '" + Name + "';";
            object value = command.ExecuteScalar();
            if (value != null)
                return value.ToString();
            else
                return "<error>";
        }
    }
}
